package algorithm.swordoff;

import algorithm.leetcode.ListNode;

/**
 * 合并两个排序的链表
 */

public class SQ25 {

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(-1);
        ListNode curr = head;


        // 合并链表的逻辑: 先把已合并好的链表末尾(这里是curr)续上较小的那个节点,然后l1或者l2,curr指向的节点分别顺次后移
        while (l1 != null || l2 != null) {
            // 两个链表都还有
            if (l1 != null && l2 != null) {
                if (l1.val <= l2.val) {
                    curr.next = l1; // 续上较小的节点
                    l1 = l1.next; // 顺次后移
                } else {
                    curr.next = l2;
                    l2 = l2.next; // 顺次后移
                }
            }

            // 只剩l2有
            else if (l1 == null) {
                curr.next = l2;
                l2 = l2.next;
            }

            // 只剩l1有
            else {
                curr.next = l1;
                l1 = l1.next;
            }
            curr = curr.next; // 顺次后移
        }
        return head.next;
    }

}
